package com.kedacom.ctsp.authz.security.provider;

import com.alibaba.fastjson.JSONObject;
import com.kedacom.ctsp.authz.entity.AuthUser;
import com.kedacom.ctsp.authz.security.captcha.CaptchaService;
import com.kedacom.ctsp.authz.security.util.AccessLoggerConstant;
import com.kedacom.ctsp.lang.StringUtil;
import com.kedacom.ctsp.lang.exception.CommonException;
import com.kedacom.ctsp.logging.AccessLogger;
import com.kedacom.ctsp.starter.springboot.CorsProperties;
import com.kedacom.ctsp.web.controller.message.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 登录失败自定义处理
 *
 * @author sunchenjie
 * @date 2017-12-07
 */
@Slf4j
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Autowired(required = false)
    private CorsProperties corsProperties;

    @Autowired(required = false)
    private CaptchaService captchaService;

    @AccessLogger(value = AccessLoggerConstant.Module.LOGIN_FAIL, describe = AccessLoggerConstant.Module.LOGIN_FAIL)
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setCharacterEncoding("UTF-8");

        // 登录错误次数+1
        if (captchaService != null) {
            captchaService.addLoginWrongTimes(request.getSession());
        }

        String errorMsg = StringUtil.format("auth.authz.username_password_error");
        // 自定义错误
        if (exception != null && exception.getCause() != null) {
            log.error("error: ", exception);
            if (exception.getCause() instanceof CommonException) {
                CommonException ex = (CommonException) exception.getCause();
                errorMsg = ex.getMessage();
            }
        }

        log.info("AuthenticationFailure");


        // 返回值
        ResponseMessage<AuthUser> error = ResponseMessage.error(HttpStatus.BAD_REQUEST.value(), errorMsg);
        response.getWriter().println(JSONObject.toJSON(error));
    }

}  